package com.kai.steering.common.web.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kai.steering.common.web.dto.QueryParam;
import com.kai.steering.common.web.service.BaseService;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @ Author     ：LiuKai.
 * @ Date       ：Created in 11:05 2022-2-22
 * @ Description：基础服务类
 * @ Modified By：
 * @Version:
 */
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements BaseService<T> {

    protected Page setPageParam(QueryParam queryParam) {
        return setPageParam(queryParam, null);
    }

    protected Page setPageParam(QueryParam queryParam, OrderItem defaultOrder) {
        Page page = new Page();
        // 设置当前页码
        page.setCurrent(queryParam.getPageNo());
        // 设置页大小
        page.setSize(queryParam.getPageSize());

        List<OrderItem> orderItems = queryParam.getOrders();
        if (orderItems != null && !orderItems.isEmpty()) {
            page.setOrders(orderItems);
        } else {
            page.setOrders(Arrays.asList(defaultOrder));
        }

        return page;
    }

    /**
     * 获取当前请求
     *
     * @return request
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取当前请求
     *
     * @return response
     */
    public HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

}

